<template>
  <el-dialog :title="isEDit ? '修改项目' : '添加项目'" center width="80%" class="dialogClass" modal-append-to-body
    :visible.sync="dialogFormVisible" :before-close="handleClose" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :model="form" :rules="rules" label-width="180px" ref="ruleForm">
      <el-row>
        <el-col :span="12">
          <el-form-item label="服务类型" prop="category_type">
            <el-select v-model="form.category_type" disabled placeholder="请选择">
              <el-option v-for="item in typeArr" :key="item.code" :label="item.name" :value="item.code">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属分类" prop="category_id">
            <el-select v-model="form.category_id" placeholder="请选择" @change="handleChange">
              <el-option v-for="item in cateList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model.trim="form.name" autocomplete="off" placeholder="请输入项目名称" style="width: 100%"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="是否允许退款" prop="allow_refund">
            <el-select v-model="form.allow_refund" placeholder="请选择">
              <el-option v-for="item in allowRefundArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否必填病情描述及备注" prop="patient_status_required">
            <el-select v-model="form.patient_status_required" placeholder="请选择">
              <el-option v-for="item in allowRefundArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否必填就医证明" prop="patient_pic_required">
            <el-select v-model="form.patient_pic_required" placeholder="请选择">
              <el-option v-for="item in allowRefundArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否具有报告" prop="report_type">
            <el-select v-model="form.report_type" placeholder="请选择">
              <el-option v-for="item in reportArr" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--   <el-col :span="12" v-if="form.allow_refund == 1">
          <el-form-item label="退款时间限制(h)" prop="before_time">
            <el-input
              v-model.trim="form.before_time"
              placeholder="请输入"
              type="number"
              style="width: 100%"
            ></el-input>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="图标" prop="icon">
            <ImgUploadPath ref="ImgUploadPath" :limit="1" @success="onUploadSuccess" @remove="onUploadRemove"
              :imgsDefalut="imgsDefalut" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sale" label="是否上架">
            <el-switch v-model="form.sale" :active-value="1" :inactive-value="0">
            </el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="项目介绍" prop="intro">
        <el-input v-model.trim="form.intro" placeholder="请输入项目介绍" type="textarea" rows="8"></el-input>
      </el-form-item>

      <el-form-item label="注意事项">
        <div class="add-table">
          <el-button class="mb10" size="mini" type="primary" @click="addPrecautions('')">新 增</el-button>
          <el-table :data="tableDataPre" stripe highlight-current-row border ref="addPrecautionsRef">
            <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
            <el-table-column align="center" v-for="(item, index) in dataListArr" :prop="item.code" :label="item.name"
              :key="index">
              <template slot-scope="scope">
                <div>
                  <el-input v-model="scope.row[item.code]"></el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" icon="el-icon-delete"
                  @click="handleDeleteRow(scope.$index, tableDataPre)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-card>
        <div style="border: 1px solid #e5e5e5;padding: 20px 0">
          <el-form-item label="价格分类">
            <div class="add-table">
              <el-button class="mb10" size="mini" type="primary" @click="addTableRow">新 增</el-button>
              <el-table :data="tableData" stripe highlight-current-row border ref="addTableRowRef">
                <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
                <el-table-column align="center" v-for="(item, index) in dataList" :prop="item.code" :label="item.name"
                  :key="index">
                  <template slot-scope="scope">
                    <div v-if="item.code == 'price1'">
                      <el-input type="number" style="width: 100%;" v-model="scope.row[item.code]"></el-input>
                    </div>
                    <div v-else>
                      <el-select v-model="scope.row[item.code]" :placeholder="item.text" filterable allow-create
                        clearable>
                        <el-option v-for="(items, optionsIndex) in projectArr" :key="optionsIndex" :label="items.name"
                          :value="items.name">
                        </el-option>
                      </el-select>
                      <!--  <el-input v-model="scope.row[item.code]"></el-input> -->
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger" icon="el-icon-delete" :disabled="scope.$index == '0'"
                      @click="handleDeleteRow(scope.$index, tableData)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <el-form-item label="耗材费用">
            <div class="add-table">
              <el-button class="mb10" size="mini" type="primary" @click="addPrecautions('consumablesArr')">新
                增</el-button>
              <el-table :data="consumablesTable" stripe highlight-current-row border ref="addPrecautionsRef">
                <el-table-column type="index" label="序号" align="center" width="50"></el-table-column>
                <el-table-column align="center" v-for="(item, index) in consumablesArr" :prop="item.code"
                  :label="item.name" :key="index">
                  <template slot-scope="scope">
                    <div v-if="item.code == 'price1'">
                      <el-input type="number" style="width: 100%;" v-model="scope.row[item.code]"></el-input>
                    </div>
                    <div v-else>
                      <el-input style="width: 100%;" v-model="scope.row[item.code]"></el-input>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="danger" icon="el-icon-delete"
                      @click="handleDeleteRow(scope.$index, consumablesTable)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form-item>
          <div style="display: flex;align-items: center;justify-content: center;font-size: 25px;font-weight: bold">合计：
            <span style="color: red;">{{sumNum}}元</span>
          </div>
          <commonAmout label="可选费用" @getVal="getVal($event)" :getValPrice="getValPrice" />

          <div style="height: 80px;"></div>
        </div>
      </el-card>
      <!--     <el-form-item label="服务内容" prop="service">
        <Editor
          ref="editorBar"
          v-if="dialogFormVisible"
          v-model="form.service"
        ></Editor>
      </el-form-item> -->
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">返回</el-button>
      <el-button :loading="btnLoading" type="primary" @click="submitForm('ruleForm')" v-no-more-click:3000>确
        定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { debounce } from "@u";
import { ApiItemAdd, ApiItemEdit, Apipermission, ApiCateList } from "@a";
import Editor from "@/components/editor.vue";
import ImgUploadPath from "@/components/imgUpload-path.vue";
import commonAmout from "@/components/commonAmout.vue"

export default {
  components: {
    Editor,
    ImgUploadPath,
    commonAmout
  },
  data() {
    return {
      sum: 0,
      sumPre: 0,
      getValPrice: 0,
      tableData: [],
      tableDataPre: [],
      dataList: [
        { code: "sku_name", name: "项目名称" },
        { code: "price1", name: "价格" },
      ],
      //注意事项
      dataListArr: [
        { code: "sku_name", name: "事项名称" },
        { code: "price1", name: "事项介绍" },
        /*{ code: "matter_price", name: "事项详情" }, */
      ],
      //医疗费用
      projectArr: [
        { name: "出诊服务费", code: "1" },
        { name: "交通费", code: "2" },
        { name: "项目服务费", code: "4" },
        /*    { name: "保险", code: "5" }, */
      ],
      //耗材费用
      consumablesArr: [
        { name: "服务名称", code: "sku_name" },
        { name: "价格", code: "price1" },
      ],

      //服务类型
      typeArr: [{ name: '医疗服务', code: '医疗服务' }, { name: '护理服务', code: '护理服务' }],
      consumablesTable: [],
      imgsDefalut: [],
      options: [],
      cateList: [],
      saleArr: [
        { name: "是", id: 1 },
        { name: "否", id: 0 },
      ],

      allowRefundArr: [
        { name: "是", id: 1 },
        { name: "否", id: 0 },
      ],

      reportArr: [
        { name: "无", id: '无' },
        { name: "影像报告", id: '影像报告' },
        { name: "化验报告", id: '化验报告' },
      ],
      permissions_loading: false,
      isEDit: false,
      idObj: {},
      btnLoading: false,
      dialogFormVisible: false,
      oldform: {
        category_id: "",
        name: "",
        sale: "",
        icon: "",
        intro: "",
        patient_status_required: "",
        patient_pic_required: "",
        category_type: '',
        /*    service: "", */
        /*   price1: "",
        price2: "",
        price3: "",
        price4: "", */
        /*   simple_intro: "", */
        /*   before_time: "", */
        allow_refund: 1,
        report_type: '无',
      },
      form: {},

      rules: {
        category_type: [
          {
            required: true,
            message: "请选择服务类型",
            trigger: ["input", "change"],
          },
        ],
        category_id: [
          {
            required: true,
            message: "请选择所属分类",
            trigger: ["input", "change"],
          },
        ],
        name: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: ["blur", "change"],
          },
        ],
        sale: [
          {
            required: true,
            message: "请选择是否上架",
            trigger: ["blur", "change"],
          },
        ],
        intro: [
          {
            required: true,
            message: "请输入项目介绍",
            trigger: "blur",
          },
        ],
        /*   before_time: [
          {
            required: true,
            message: "请输入退款时间限制",
            trigger: "blur",
          },
        ], */

        allow_refund: [
          {
            required: true,
            message: "请选择",
            trigger: "blur",
          },
        ],

        patient_status_required: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],

        patient_pic_required: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],

        report_type: [
          {
            required: true,
            message: "请选择",
            trigger: "change",
          },
        ],


        service: [
          {
            required: true,
            message: "请输入服务内容",
            trigger: "blur",
          },
        ],
        price1: [
          {
            required: true,
            message: "请输入出诊费",
            trigger: ["blur", "change"],
          },
        ],
        price2: [
          {
            required: true,
            message: "请输入交通费",
            trigger: ["blur", "change"],
          },
        ],
        price3: [
          {
            required: true,
            message: "请输入治疗费",
            trigger: ["blur", "change"],
          },
        ],
        price4: [
          {
            required: true,
            message: "请输入耗材费",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },

  methods: {
    handleChange(e) {
      console.log(e)
      let a = this.cateList.find(item => {
        if (item.id == e) {
          return item
        }
      })
      this.form.category_type = a.type
    },

    //退款申请
    getVal(val) {
      this.getValPrice = val
    },

    /*    beForFilter(v) {
      this.projectArr.push({
        label: v,
        name: "自定义",
        value: v,
      });
    }, */
    //添加项目价格
    addTableRow() {
      var addObj = {
        sku_name: "",
        price1: "0",
      };
      this.tableData.push(addObj);
    },
    //添加项目介绍
    addPrecautions(val) {
      /*  { code: "matter_name", name: "事项名称" },
        { code: "matter_Introduction", name: "事项介绍" },
        { code: "matter_price", name: "事项详情" }, */

      var addObj = {
        sku_name: "",
        price1: " ",
      };
      if (val == "consumablesArr") {
        this.consumablesTable.push(addObj);
      } else {
        this.tableDataPre.push(addObj);
      }
    },

    handleDeleteRow(index, rows) {
      rows.splice(index, 1);
    },
    onUploadSuccess(path) {
      console.log(path);
      this.form.icon = path;
    },
    onUploadRemove() {
      this.form.icon = "";
    },

    getCateList() {
      ApiCateList().then((res) => {
        this.cateList = res.data;
      });
    },
    remoteMethod(query = "") {
      query = query.trim();
      if (query !== "") {
        this.permissions_loading = true;
        Apipermission({ name: query }).then((res) => {
          this.options = res.data || [];
          this.$nextTick((_) => {
            this.permissions_loading = false;
          });
        });
      } else {
        this.options = [];
      }
    },
    showDialog(row) {
      const data = row || this.oldform;
      for (const key in this.oldform) {
        this.$set(this.form, key, data[key]);
      }

      if (data.id) {
        this.isEDit = true;
        this.id = data.id;
        //可选费用
        this.getValPrice = data.extend_price


        //价格回显
        if (data.price_detail && data.price_detail.length > 0) {
          this.tableData = [];
          let val = JSON.parse(data.price_detail);
          let dataVal = [];
          for (const key in val) {
            dataVal.push({
              sku_name: key.trim(),
              price1: val[key],
            });
          }
          this.tableData = dataVal;
        }

        //耗材费回显
        if (
          data.material_price_detail &&
          data.material_price_detail.length > 0
        ) {
          this.consumablesTable = [];
          let val = JSON.parse(data.material_price_detail);
          let dataVal = [];
          for (const key in val) {
            dataVal.push({
              sku_name: key.trim(),
              price1: val[key],
            });
          }
          this.consumablesTable = dataVal;
        }
        if (data.icon) this.imgsDefalut = [{ url: this.$path + data.icon }];
        //注意事项回显
        if (data.warning) {
          this.tableDataPre = [];
          let val = JSON.parse(data.warning);
          this.tableDataPre = val;
        }
      } else {
        this.isEDit = false;
      }
      /*  this.resetForm("ruleForm"); */
      this.dialogFormVisible = true;
      this.getCateList();
    },

    // 提交数据
    submitForm: debounce(
      function (formName) {
        console.log(this.tableDataPre);
        this.$refs[formName].validate((valid) => {
          let val = this.forMatterData(this.tableData);
          let consumables = this.forMatterData(this.consumablesTable);
          let valPre = this.tableDataPre;
          if (valid) {
            this.btnLoading = true;
            const form = {
              ...this.form,
              //价格详情
              price_detail: JSON.stringify(val),
              //注意事项
              warning: JSON.stringify(valPre),
              //耗材费
              material_price_detail: JSON.stringify(consumables),
              //其他费用
              extend_price: this.getValPrice
            };
            console.log(this.isEDit);
            if (this.isEDit) {
              this.editData(form);
            } else {
              this.addData(form);
            }
          } else {
            return false;
          }
        });
      },
      300,
      true
    ),

    //转换keyValue形式
    checkItem(item) {
      const values = Object.values(item);
      return { [values[0]]: values[1] };
    },

    forMatterData(data) {
      let val = {};
      data.forEach((item) => {
        val[item.sku_name + " "] = item.price1;
      });
      return val;
    },

    addData(parmas) {
      ApiItemAdd(parmas)
        .then((res) => {
          this.changeData();
        })
        .finally((_) => {
          this.btnLoading = false;
        });
    },
    editData(parmas) {
      ApiItemEdit(parmas, this.id)
        .then((res) => {
          this.changeData();
        })
        .finally((_) => {
          this.btnLoading = false;
        });
    },
    changeData() {
      this.$message.success("操作成功！");
      this.$emit("changeList");
      this.handleClose();
    },
    handleClose() {
      this.resetForm();
    },
    resetForm() {
      this.dialogFormVisible = false;
      this.form = { ...this.oldform };
      this.tableData = [];
      this.tableDataPre = [];
      this.consumablesTable = [];
      this.$nextTick((_) => {
        this.$refs.ruleForm.clearValidate();
        this.$refs.ImgUploadPath.clear();
      });
    },
  },
  computed: {
    sumNum() {
      return this.sum + this.sumPre
    }
  },
  watch: {
    tableData: {
      deep: true,
      immediate: true,
      handler(val, oldval) {
        if (val) {
          this.sum = 0
          val.forEach(item => {
            this.sum += Number(item.price1)
          })
        }

      }
    },
    consumablesTable: {
      deep: true,
      immediate: true,
      handler(val, oldval) {
        if (val) {
          this.sumPre = 0
          val.forEach(item => {
            this.sumPre += Number(item.price1)
          })
        }

      }
    }
  },

};
</script>
<style lang="less" scoped>
.dialogClass {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  /*   height: 1800px; */
  ::v-deep .el-dialog {
    margin: 0 auto !important;
    height: 80%;
    overflow: hidden;
    /*   background-color: black; */
    .el-dialog__body {
      position: absolute;
      left: 0;
      top: 54px;
      bottom: 0;
      right: 0;
      padding: 0;
      z-index: 1;
      overflow: hidden;
      overflow-y: auto;
      // 下边设置字体，我的需求是黑底白字
      color: #ffffff;
      line-height: 30px;
      padding: 0 15px;
    }
  }
}
/* 使顶部进行吸顶 */
.top {
  position: sticky;
  position: -webkit-sticky;
  top: 0px;
}
/* 表单大小设置 */
/* .dialogClass {
  height: 90%;
  overflow: scroll-y;
  margin: auto;
} */
/* .el-dialog__body {
  position: absolute;
  left: 0;
  top: 54px;
  bottom: 70px;
  right: 0;
  padding: 0;
  z-index: 1;
  overflow: hidden;
  overflow-y: auto;
} */

/**表单 确定和取消 按钮的位置 */
.dialog-footer {
  position: absolute;
  z-index: 1000;
  bottom: 20px;
  margin: auto;
  transform: translate(-20px);
  width: 100%;
  margin-bottom: 20px;
  /*   left: 50%; */
  /*  
  margin-top: 50px; */
  /*   left: 0;
  right: 0;
  bottom: 0; */
}

/* 表单输入框的大小 */
.el-input {
  width: 50%;
}

/* 弹出框滚动条 */
/* 设置滚动条的样式 */
/**解决了滚动条之间发生错位的现象 */
::-webkit-scrollbar {
  width: 10px !important;
  height: 10px !important;
  border-radius: 5px;
}
::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.2);
  /* 滚动条的颜色 */
  background-color: #e4e4e4;
}
</style>
